#include "MainWindow.h"
#include "common/CustomMessageBox.h"
#include "SteelClientDataProvider.h"
#include <QApplication>
#include <QPainter>
#include <QFont>
#include <QPalette>
#include <QGraphicsDropShadowEffect>
#include <QScreen>
#include <QKeyEvent>
#include <QString>
#include <cstring>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_centralWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_topBarWidget(nullptr)
    , m_contentStack(nullptr)
    , m_loginWidget(nullptr)
    , m_mainPageWidget(nullptr)
{
    setupUI();
    setupConnections();
    
    // 设置窗口属性 - 无标题栏全屏显示
    setWindowTitle("智慧炼钢系统");
    
    setWindowFlags(Qt::FramelessWindowHint);
    // setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    
    // 全屏显示
    showFullScreen();
}

MainWindow::~MainWindow()
{
}

MainPageWidget* MainWindow::getMainPageWidget() const
{
    return m_mainPageWidget;
}

void MainWindow::setupUI()
{
    // 设置中央部件
    m_centralWidget = new QWidget(this);
    setCentralWidget(m_centralWidget);
    
    // 主布局
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    
    m_topBarWidget = new TopbarWidget(m_centralWidget);
    m_topBarWidget->setTitle(QString("智慧炼钢系统登陆界面"));
    
    setupContentArea();
}


void MainWindow::setupContentArea()
{
    // 内容区域 - 使用StackedWidget管理不同页面
    m_contentStack = new QStackedWidget(m_centralWidget);
    m_contentStack->setObjectName("contentStack");
    
    // 登录界面
    m_loginWidget = new LoginWidget(this);
    m_contentStack->addWidget(m_loginWidget);
    
    // 主页面
    m_mainPageWidget = new MainPageWidget(this);
    m_contentStack->addWidget(m_mainPageWidget);
    
    // 默认显示登录界面
    m_contentStack->setCurrentWidget(m_loginWidget);
    
    // 添加到主布局 - 垂直布局：顶部栏 + 内容区域
    m_mainLayout->addWidget(m_topBarWidget);
    m_mainLayout->addWidget(m_contentStack);
}

void MainWindow::setupConnections()
{
    // 登录界面连接
    connect(m_loginWidget, &LoginWidget::loginRequested, this, &MainWindow::onLoginSuccess);
    connect(m_loginWidget, &LoginWidget::forgotPasswordClicked, this, &MainWindow::onForgotPassword);
    
    // 主页面连接
    connect(m_mainPageWidget, &MainPageWidget::logoutRequested, this, &MainWindow::onLogoutRequested);
    connect(m_mainPageWidget, &MainPageWidget::moduleSelected, this, &MainWindow::onModuleSelected);
    connect(m_mainPageWidget, &MainPageWidget::navigationSelectedByIndex, this, &MainWindow::onNavigationSelectedByIndex);
    
    // 顶部栏连接
    connect(m_topBarWidget, &TopbarWidget::exitRequested, this, &MainWindow::onExitApplication);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
    update(); // 触发重绘以更新背景
}

void MainWindow::onLoginSuccess()
{
    QString username = m_loginWidget->getUsername();
    QString password = m_loginWidget->getPassword();
    
    // 转换为UTF-8编码的C字符串
    QByteArray usernameBytes = username.toUtf8();
    QByteArray passwordBytes = password.toUtf8();
    const char* usernameStr = usernameBytes.constData();
    const char* passwordStr = passwordBytes.constData();
    
    // 调用登录验证回调
    char errorMessage[256] = {0};
    bool loginSuccess = SteelClientData::validateLogin(usernameStr, passwordStr, errorMessage, sizeof(errorMessage));
    
    if (loginSuccess) {
        // 登录成功
        m_contentStack->setCurrentIndex(1);
        m_topBarWidget->setUserInfo(username);
        m_topBarWidget->setPhoto(":/img/images/icon-user.png");
        m_topBarWidget->showSeparator(true);
        if (m_mainPageWidget && m_mainPageWidget->getNavigationWidget()) {
            m_mainPageWidget->getNavigationWidget()->setSelectedItemByIndex(0, 0);
        }
    } else {
        // 登录失败，显示错误消息
        QString errorMsg = QString::fromUtf8(errorMessage);
        if (errorMsg.isEmpty()) {
            errorMsg = "用户名或密码错误！";
        }
        CustomMessageBox::warning(this, "登录失败", errorMsg);
    }
}

void MainWindow::onLoginFailed()
{
    CustomMessageBox::warning(this, "登录失败", "登录失败，请检查用户名和密码！");
}

void MainWindow::onForgotPassword()
{
    CustomMessageBox::information(this, "忘记密码", "请联系系统管理员重置密码！");
}

void MainWindow::onExitApplication()
{
    if (CustomMessageBox::question(this, "确认退出", "确定要退出智慧炼钢系统吗？") == CustomMessageBox::Yes) {
        SteelClientData::notifyApplicationShutdown();
        QApplication::quit();
    }
}

void MainWindow::onLogoutRequested()
{
    if (CustomMessageBox::question(this, "退出登录", "确定要退出登录吗？") == CustomMessageBox::Yes) {
        // 返回到登录界面
        m_contentStack->setCurrentIndex(0);
        m_topBarWidget->setTitle("智慧炼钢系统登录界面");
        m_topBarWidget->setUserInfo("鑫达 | 五号炉");
        m_loginWidget->clearForm();
    }
}

void MainWindow::onModuleSelected(const QString &moduleName)
{
}

void MainWindow::onNavigationSelectedByIndex(int stoveIndex, int pageIndex)
{
    QStringList chineseNumbers = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
    QString stoveName;
    if (stoveIndex >= 0 && stoveIndex < chineseNumbers.size()) {
        stoveName = QString("%1号转炉").arg(chineseNumbers[stoveIndex]);
    } else {
        stoveName = QString("%1号转炉").arg(stoveIndex + 1);
    }
    QString pageName;
    
    switch (pageIndex) {
        case 0: pageName = "冶炼配置界面"; break;
        case 1: pageName = "主操作界面"; break;
        case 2: pageName = "冶炼追溯界面"; break;
        default: pageName = QString("页面%1").arg(pageIndex + 1); break;
    }
    
    // 更新顶部栏的炉子信息
    m_topBarWidget->setStoveInfo(stoveName);
    
    // 更新标题，包含页面信息
    QString newTitle = QString("智慧炼钢系统%1").arg(pageName);
    m_topBarWidget->setTitle(newTitle);
    
    qDebug() << "Navigation selected by index - Stove:" << stoveIndex << "Page:" << pageIndex << "->" << stoveName << "-" << pageName;
}
